const https = require('https');
const http = require('http');
const qs = require('querystring');
require('chromedriver');
const { Builder, By, Key, until } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const { resolve } = require('path');
const { rejects } = require('assert');
const { addConsoleHandler } = require('selenium-webdriver/lib/logging');
const { pushLog,clearLog} = require('./middleware/log');
const adConfig = require('./config/adConfig');
const userDict = require("./config/user");
const user = require('./config/user');
const { push } = require('./config/user');
const browser = new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless().windowSize({ height: 1000, width: 1080 }));
var appList = null;//应用列表
var driver = null;
var runingStatus = false;
// var driver = new Builder().forBrowser('chrome').build();
var adList = null; // 待创建的广告位列表
var pageData = {
    pageIndex: 0,
    pageSize: 0,
}
var taskDtaList = [];

//账号列表
var userLogin = [];
//当前登录账号信息
var loginInfo = null;
//打开浏览器
function open(list) {
    clearLog();
    adList = list;
    userLogin = createUsers();
    if (userLogin.length == 0) {
        return
    }
    loginInfo = {
        status: 0,
        index: 0,
        userInfo: userLogin[0]
    }
    if(runingStatus){
        pushLog("当前脚本正在执行中请耐心等待任务结束");
        return
    }
    runingStatus = true;
    driver = browser.build();
    driver.get("https://e.qq.com/dev/index.html").then(() => {
        pushLog("页面加载完成");
        auth();
    });
}

//构造任务数据
/**
 * parmars {Arr}
 */
function createTaskData() {
    try {
        let userInfo = loginInfo.userInfo;
        let taskD = adList['accounts'][userInfo.qq];
        let taskList = [];
        let tempData = null;
        taskD.forEach(item => {
            tempData = adConfig[item.adType];
            appList.forEach(appitem => {
                if (appitem.outerMediumId == item.appCode) {
                    tempData['newPlacementAddVo'].mediumId = appitem.mediumId;
                    tempData['newPlacementAddVo'].memberId = userInfo.memberId;
                    tempData['newPlacementAddVo'].placementName = item.slotName;
                }
            })
            taskList.push(tempData);
        })
        pushLog(loginInfo.userInfo.qq + "：任务创建成功...");
        return taskList;
    } catch (error) {
        pushLog("构造模板数据异常" + error.toString());

        return [];
    }
}
//创建任务账号

function createUsers() {
    let users = []
    console.log(JSON.stringify(adList['accounts']));
    userDict.forEach(item => {
        if (JSON.stringify(adList) != "{}") {
            console.log(item.qq);
            console.log(JSON.stringify(adList['accounts'][item.qq]));
            if (typeof adList['accounts'][item.qq] == "object") {
                users.push(item);
            }
        }

    })
    if (users.length == 0) {
        pushLog("无可用账号");

    } else {
        pushLog("参与的任务账号：" + JSON.stringify(users));
    }
    return users;
}

//去授权页面
function auth() {

    driver.findElement(By.id('loginBtn')).click();
    console.log("进入授权页面");
    pushLog("进入授权页面");
    driver.sleep(2000).then(() => {
        iframe = driver.findElement(By.id("ptlogin_iframe"));
        driver.switchTo().frame(iframe).then(() => {
            login();
        });

    });
}

//获取填充的cookies

function getCookie() {
    console.log('正在获取cookies');
    pushLog("正在获取cookies");
    return driver.manage().getCookies();
}


async function sycnData(cookie) {
    let cookies=cookie;
    console.log("同步数据的cookie"+cookies);
    console.log("同步数据的menberId"+loginInfo.userInfo.memberId);
    let reportAdList = {};
    //获取广告位列表
    await formAjax(https,
        {
            searchCriteria: "",
            pageIndex: 0,
            pageSize: pageData.pageSize,
            memberId: loginInfo.userInfo.memberId
        },
        cookies,
        {
            hostname: 'adnet.qq.com',
            port: 443,
            path: '/placement/search',
            method: 'POST',
        },
        {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
            "Referer": "https://adnet.qq.com/placement/0/add",
            "Origin": "https://adnet.qq.com",
            "Host": "adnet.qq.com",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "cookie": cookies
        }
    ).then(res => {
        pageData = {
            pageIndex: 0,
            pageSize: 0,
        }
        if (res.ret == 0) {
            pushLog(loginInfo.userInfo.qq + "：广告位列表获取成功");
            reportAdList = res;
        } else {
            reportAdList = {};
            pushLog(loginInfo.userInfo.qq + "：广告位列表获取失败");
        }
        console.log("广告位列表" + JSON.stringify(res));
    }).catch(err => {
        pageData = {
            pageIndex: 0,
            pageSize: 0,
        }
        console.log("获取广告位列表失败" + JSON.stringify(err));
    })

    if (JSON.stringify(reportAdList) !== "{}") {
        //同步广告位数据
        await formAjax(http,
            {
                header: { token: adList.token },
                body: reportAdList,
                string: true
            }
            ,"",
            {
                hostname: '10.0.0.141',
                port: 8081,
                path: '/source/app/slot/private/import/autoconfig.do',
                method: 'POST',
            },
            {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
                "Referer": "https://10.0.0.141:8081",
                "Origin": "https://10.0.0.141:8081",
                "Host": "10.0.0.141:8081",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "cookie": ""
            }).then((res) => {
                if (res.code == 0) {
                    pushLog(loginInfo.userInfo.qq+"：数据同步成功")
                } else {
                    pushLog(loginInfo.userInfo.qq+"：数据同步失败"+JSON.stringify(res));
                }
                // console.log(res)
            });


    }else{
        pushLog(loginInfo.userInfo.qq+"：数据未同步")
    }
}

//退出登录
async function loginOut(cookie) {
    if (loginInfo.index < (userLogin.length - 1) || loginInfo.index == 0) {
        pushLog("正在获取" + loginInfo.userInfo.qq + "创建的广告位");
        //同步数据
        await sycnData(cookie);
        let newloginInfo = {
            status: 0,
            index: loginInfo.index + 1,
            userInfo: userLogin[loginInfo.index + 1]
        }
        loginInfo = newloginInfo;
        await driver.get("https://adnet.qq.com/user/logout");
        pushLog(loginInfo.userInfo.qq+"：退出登录")
        auth();

    } else {
        if (loginInfo.index == (userLogin.length - 1)) {
            //同步数据
           await sycnData(cookie);
        }
        if (loginInfo.index >= (userLogin.length - 1)) {
           
            loginInfo = {
                status: 0,
                index: 0,
                userInfo: userLogin[0]
            }
            driver.close();
            runingStatus = false;
            pushLog("任务结束...");
        }

    }

}
//授权登录
function login() {
    let cookie = "";
    (async function isPageload() {
        await driver.findElement(By.id("qlogin_list")).findElement(By.xpath("//a[@uin=" + loginInfo.userInfo.qq + "]")).then(el => {
            driver.executeScript("arguments[0].click()", el).then(() => {
                driver.switchTo().defaultContent();
            });
        }).catch(() => {
            console.log("没有找到账号");
            pushLog("没有找到账号");
        });
        console.log("开始登录")
        let as = await driver.wait(until.elementLocated(By.id('messageCenter')), 1000 * 60).catch(() => { console.log("登录失败") });
        if (!as) return;
        console.log(loginInfo.userInfo.qq + "登录成功", as.getId());
        pushLog(loginInfo.userInfo.qq + "：登录成功");
        if (!cookie)
            await getCookie().then(res => {
                res.forEach((item, index) => {
                    if (index == res.length - 1) {
                        cookie += (item.name + "=" + item.value);
                    } else {
                        cookie += (item.name + "=" + item.value + "; ")
                    }
                })
            });


        /**
         *  接口调试区域 </>
         * 
        

        await formAjax(http,
            {

                header: { token: adList['token'] },
                body: {
                    name: "fanjiantao",
                },
                string: true,

            }
            , "",
            {
                hostname: '10.0.0.141',
                port: 8081,
                path: '/source/app/slot/private/import/autoconfig.do',
                method: 'POST',
            },
            {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
                "Referer": "https://10.0.0.141:8081",
                "Origin": "https://10.0.0.141:8081",
                "Host": "10.0.0.114:8081",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "cookie": ""
            }).then((res) => {
                console.log(res)
            });

        return
         */

        // sycnData(cookie);

        // return;



        //获取应用列表
        await ajax(https, "", cookie, {
            hostname: 'adnet.qq.com',
            port: 443,
            path: '/medium/list/' + loginInfo.userInfo.memberId,
            method: 'GET',
        }).then(res => {
            pushLog("应用列表请求完成：" + res.message);
            if (res.ret == 0) {
                appList = res.data;
                // console.log(typeof appList,"应用列表")
            }
        }).catch(err => {
            pushLog("获取应用列表失败:" + JSON.stringify(err));

        })

        //生成任务列表 
        taskDtaList = createTaskData();
        //创建代码
        async function create() {
            await driver.sleep(3000).then(() => {
                console.log("任务信息" + JSON.stringify(taskDtaList))
                let task = taskDtaList.pop();
                console.log("当前创建的广告位信息" + JSON.stringify(task));
                if (typeof task !== "undefined") {
                    pushLog("创建广告位中....");
                    ajax(https, task, cookie).then((res) => {
                        if (res.ret == 0) {
                            pageData.pageSize = pageData.pageSize + 1
                            pushLog("操作完成：" + res.message + "[" + (res.data.length > 0 ? res.data[0] : '') + "]");
                        } else {
                            pushLog("操作完成：未完成创建");
                        }
                        console.log(res);
                        create();
                    }).catch((err) => {
                        //退出装好
                        console.log(err)
                        pushLog("创建广告位失败:" + JSON.stringify(err.message));
                        create();
                    })
                } else {
                    loginOut(cookie);
                    return false
                }
            });
        }
        await create();
    })();

    function ajax(protocol, data, cookie, params) {
        let option = params || {
            hostname: 'adnet.qq.com',
            // hostname:'127.0.0.1',
            port: 443,
            path: '/placement/create',
            method: 'POST',
            // protocol: "https" //默认使用https
        }
        return new Promise((resolve, reject) => {
            var post_data = { ...data };
            var content = JSON.stringify(post_data);
            var options = {
                ...option,
                headers: {
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
                    "Referer": "https://adnet.qq.com/placement/0/add",
                    "Origin": "https://adnet.qq.com",
                    "Host": "adnet.qq.com",
                    "Content-Type": "application/json",
                    "cookie": cookie
                }
            };

            var req = protocol.request(options, function (res) {
                console.log('STATUS(响应状态): ' + res.statusCode);
                console.log('HEADERS(响应头): ' + JSON.stringify(res.headers));
                res.setEncoding('utf8');
                let resData = ""
                res.on('data', function (chunk) {
                    // console.log('BODY(响应体): ' + chunk);
                    resData += chunk;
                    // resolve(chunk);
                });
                res.on('end', function () {
                    // console.log(resData,"响应数据");
                    console.log(JSON.stringify(resData));
                    try {
                        resolve(JSON.parse(resData));
                    } catch (error) {
                        resolve({ ret: -100, message: "*******", data: [] });
                    }

                });
            });
            req.on('error', function (e) {
                console.log('problem with request(请求失败): ' + e.message);
                reject(e);
            });
            // 将数据写入请求体
            req.write(content);//注意这个地方  
            req.end();
        })
    }
}

function formAjax(protocol, data, cookie, params, headers) {
    let option = params || {
        hostname: 'adnet.qq.com',
        path: '/placement/create',
        method: 'POST',
    }
    return new Promise((resolve, reject) => {
        var post_data = { ...data };
        var content = post_data.string ? JSON.stringify(post_data) : qs.stringify(post_data);
        var options = {
            ...option,
            headers: headers || {
                "cookie": cookie
            }
        };

        var req = protocol.request(options, function (res) {
            // console.log('STATUS(响应状态): ' + res.statusCode);
            // console.log('HEADERS(响应头): ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            let resData = ""
            res.on('data', function (chunk) {
                // console.log('BODY(响应体): ' + chunk);
                resData += chunk;
                // resolve(chunk);
            });
            res.on('end', function () {
                // console.log(resData, "响应数据");
                console.log("返回的数据：" + resData);
                try {
                    resolve(JSON.parse(resData));
                } catch (error) {

                    resolve({ ret: -100, message: "*******", data: [] });
                }

            });
        });
        req.on('error', function (e) {
            console.log('problem with request(请求失败): ' + e.message);
            reject(e);
        });
        console.log("发送的数据体：", content);
        // 将数据写入请求体
        req.write(content);//注意这个地方  
        req.end();
    })
}

function getRunStatus() {
    return runingStatus;
}

process.on('uncaughtException', (err) => {
    console.log("系统异常:"+err);
    pushLog("系统异常："+JSON.stringify(err))
  
});

module.exports = { open, getRunStatus };


// https://adnet.qq.com/placement/search
// searchCriteria: 
// pageIndex: 0
// pageSize: 20
// memberId: 501050706899
